package Day2025_03_05;

import java.util.Stack;

public class LeetCode394 {
    public String decodeString(String s) {
        Stack<Integer> nums = new Stack<>();
        Stack<StringBuffer> ret = new Stack<>();
        ret.push(new StringBuffer());
        char[] ch = s.toCharArray();
        int n = ch.length;
        int i = 0;
        while (i < n) {
            if (ch[i] >= '0' && ch[i] <='9') {
                int tmp = 0;
                while (i < n && ch[i] >= '0' && ch[i] <='9') {
                    tmp = tmp * 10 + (ch[i] - '0');
                    i++;
                }
                nums.push(tmp);
            } else if (ch[i] == '[') {
                i++;
                StringBuffer tmp = new StringBuffer();
                while (i < n && ch[i] >= 'a' && ch[i] <= 'z') {
                    tmp.append(ch[i]);
                    i++;
                }
                ret.push(tmp);
            } else if (ch[i] == ']') {
                StringBuffer tmp = ret.pop();
                int k = nums.pop();
                while (k != 0) {
                    ret.peek().append(tmp);
                    k--;
                }
                i++;
            } else {
                StringBuffer tmp = new StringBuffer();
                while (i < n && ch[i] >= 'a' && ch[i] <= 'z') {
                    tmp.append(ch[i]);
                    i++;
                }
                ret.peek().append(tmp);
            }
        }
        return ret.peek().toString();
    }
}
